<?php

namespace maotool\util;

use maotool\file\FileUtil;

class AddressUtil
{
    /**
     * 解析地址字符串，提取省市区等标准地址信息
     *
     * @param string $address 待解析的地址字符串
     * @return array 返回解析后的标准地址信息数组，包含省、市、区及详细地址等信息
     */
    public function parse($address)
    {
        // 获取省市区数据树
        $pcaTree = $this->getProvinceCityDistrictTree();

        $result = [
            'province' => '',
            'province_code' => '',
            'city' => '',
            'city_code' => '',
            'district' => '',
            'district_code' => '',
            'street' => '',
            'detail' => trim($address)
        ];

        if (empty($address) || empty($pcaTree)) {
            return $result;
        }

        // 特殊处理直辖市（北京、天津、上海、重庆）
        $municipalities = ['北京市', '天津市', '上海市', '重庆市'];

        // 匹配省份
        foreach ($pcaTree as $province) {
            if (strpos($address, $province['name']) !== false) {
                $result['province'] = $province['name'];
                $result['province_code'] = $province['code'];
                $address = str_replace($province['name'], '', $address);

                // 处理直辖市特殊情况
                if (in_array($province['name'], $municipalities)) {
                    $result['city'] = $province['name']; // 直辖市的城市名等于省份名
                    $result['city_code'] = $province['code'];

                    // 查找具体的区县
                    if (isset($province['children'])) {
                        foreach ($province['children'] as $districtLevel) {
                            // 跳过"市辖区"这种中间层级，直接查找具体的区
                            if ($districtLevel['name'] === '市辖区' && isset($districtLevel['children'])) {
                                foreach ($districtLevel['children'] as $actualDistrict) {
                                    if (strpos($address, $actualDistrict['name']) !== false) {
                                        $result['district'] = $actualDistrict['name'];
                                        $result['district_code'] = $actualDistrict['code'];
                                        $address = str_replace($actualDistrict['name'], '', $address);
                                        break 2; // 跳出两层循环
                                    }
                                }
                            } elseif (strpos($address, $districtLevel['name']) !== false) {
                                // 正常情况下的区县匹配
                                $result['district'] = $districtLevel['name'];
                                $result['district_code'] = $districtLevel['code'];
                                $address = str_replace($districtLevel['name'], '', $address);
                                break;
                            }
                        }
                    }
                } else {
                    // 非直辖市的正常处理流程
                    // 匹配城市
                    if (isset($province['children'])) {
                        foreach ($province['children'] as $city) {
                            if (strpos($address, $city['name']) !== false) {
                                $result['city'] = $city['name'];
                                $result['city_code'] = $city['code'];
                                $address = str_replace($city['name'], '', $address);

                                // 匹配区县
                                if (isset($city['children'])) {
                                    foreach ($city['children'] as $district) {
                                        if (strpos($address, $district['name']) !== false) {
                                            $result['district'] = $district['name'];
                                            $result['district_code'] = $district['code'];
                                            $address = str_replace($district['name'], '', $address);
                                            break;
                                        }
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
                break;
            }
        }

        // 剩余部分作为详细地址
        $result['detail'] = trim($address);

        return $result;
    }


    /**
     * 判断地址中是否包含省市区信息
     *
     * @param string $address 待检测的地址字符串
     * @return bool 如果地址包含省市区信息则返回true，否则返回false
     */
    public function hasProvinceCityDistrict($address)
    {
        $parsed = $this->parse($address);
        return !empty($parsed['province']) || !empty($parsed['city']) || !empty($parsed['district']);
    }

    /**
     * 判断地址中是否包含省市区信息
     *
     * @param string $address 待检测的地址字符串
     * @return bool 如果地址包含省市区信息则返回true，否则返回false
     */
    public function hasProvinceCity($address)
    {
        $parsed = $this->parse($address);
        return !empty($parsed['province']) || !empty($parsed['city']);
    }

    /**
     * 获取省市区行政区域树形数据
     *
     * @return array 省市区树形结构数据
     */
    public function getProvinceCityDistrictTree()
    {
        return FileUtil::readJson("maotool:/src/main/resources/static/pca-code.json");
    }

    /**
     * 获取省市区街道行政区域树形数据
     *
     * @return array 省市区街道四级树形结构数据
     */
    public function getProvinceCityDistrictStreetTree()
    {
        return FileUtil::readJson("maotool:/src/main/resources/static/pcas-code.json");
    }

}
